package com.flyduck.mall.sms.config;

import cn.hutool.core.collection.ListUtil;
import com.flyduck.mall.common.core.utils.BeanUtils;
import com.flyduck.mall.pms.api.RemoteProductService;
import com.flyduck.mall.pms.api.vo.RemoteProductRespVO;
import com.flyduck.mall.sms.document.EsProductDoc;
import com.flyduck.mall.sms.repository.EsProductDocRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * SearchContextStartup
 * </p>
 *
 * @author flyduck
 * @since 2024-05-24
 */
@Slf4j
@Component
public class SearchContextStartup implements ApplicationRunner {

    @DubboReference
    private RemoteProductService remoteProductService;
    @Resource
    private EsProductDocRepository esProductDocRepository;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        esProductDocRepository.deleteAll();

        List<RemoteProductRespVO> remoteProductRespVOList = remoteProductService.getOnSaleProductList();

        List<EsProductDoc> esProductDocList = BeanUtils.toBeanList(remoteProductRespVOList, EsProductDoc.class);
        Iterable<EsProductDoc> iterable = esProductDocRepository.saveAll(esProductDocList);

        int count = ListUtil.toList(iterable).size();
        log.info("已初始化es数据{}条",count);
    }
}
